package com.meepo.feed.comment

import android.annotation.SuppressLint
import android.text.TextPaint
import android.text.style.ClickableSpan
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import com.meepo.sdk.utils.SpanUtils
import com.meepo.basic.components.listfragment.MeepoListFragment
import com.meepo.basic.router.RouterManager
import com.meepo.basic.schema.Enums
import com.meepo.basic.schema.common.PageResult
import com.meepo.basic.schema.common.ResponseWrapper
import com.meepo.basic.schema.feed.Comment
import com.meepo.feed.API
import com.meepo.feed.R
import com.meepo.feed.feed.FeedDetailActivity
import com.meepo.framework.design.imageview.CircularImage
import com.meepo.framework.design.recycler.ViewHolder
import com.xiaojinzi.component.anno.FragmentAnno
import com.xiaojinzi.component.support.ParameterSupport
import io.reactivex.Observable


@FragmentAnno(RouterManager.FeedModule.CommentListFragment_Path)
class CommentListFragment : MeepoListFragment<Comment>() {

    override fun loadDataObservable(page: Int): Observable<ResponseWrapper<PageResult<Comment>>> {
        val authorId = ParameterSupport.getString(arguments, "authorId") ?: ""

        return API.instance().fetchMainComments(authorId = authorId, page = page)
    }

    @SuppressLint("SetTextI18n")
    override fun bind(item: Comment, holder: ViewHolder, position: Int) {
        // 头像
        holder.getView<CircularImage>(R.id.avatar_ci)?.let {
            holder.setImagePath(R.id.avatar_ci, item.author?.avatar ?: "")
            it.setOnClickListener {
                item.author?.id?.let { userId ->
                    RouterManager.UserModule.routeToUserProfile(requireContext(), userId)
                }
            }
        }

        // 昵称
        holder.getView<TextView>(R.id.username_tv)?.let {
            it.text = item.author?.nickname ?: ""
            it.setOnClickListener {
                item.author?.id?.let { userId ->
                    RouterManager.UserModule.routeToUserProfile(requireContext(), userId)
                }
            }
        }

        // 喜欢 todo 渲染喜欢的代码重复多次
        holder.setText(R.id.like_count_tv, "" + item.getLikeCount())

        val likeColor = requireContext().resources.getColor(R.color.like)
        val normalColor = requireContext().resources.getColor(R.color.primary_text_color)

        holder.getView<ImageView>(R.id.like_iv)?.let { imageView ->
            if (item.isLiked()) {
                imageView.setImageResource(R.drawable.ic_like)
                imageView.setColorFilter(likeColor)
            } else {
                imageView.setImageResource(R.drawable.ic_like_line)
                imageView.setColorFilter(normalColor)
            }
        }

        holder.getView<LinearLayout>(R.id.like_ll)?.setOnClickListener {
            presenter.call(
                API.instance()
                    .addAction(item.id, Enums.ITEM_TYPE_COMMENT, Enums.ACTION_TYPE_LIKED, cancel = if (item.isLiked()) 1 else 0)
            )

            this.replace(position, item.switchLiked())
        }

        holder.getView<TextView>(R.id.like_count_tv)?.let {
            it.text = "" + item.getLikeCount()
            it.setTextColor(if (item.isLiked()) likeColor else normalColor)
        }

        // 时间
        holder.setText(R.id.time_tv, item.createdAt ?: "")

        // 评论内容
        holder.setText(R.id.content_tv, item.content ?: "")

        // 评论目标
        if (item.atComment != null) {
            holder.getView<TextView>(R.id.content_tv)?.let { textView ->

                com.meepo.sdk.utils.SpanUtils.with(textView).append("回复 ")
                    .append(" ${item.atComment?.author?.nickname ?: ""}: ")
                    .setClickSpan(object : ClickableSpan() {
                        override fun onClick(p0: View) {
                            item.atComment?.author?.id?.let {
                                RouterManager.UserModule.routeToUserProfile(requireContext(), it)
                            }
                        }

                        override fun updateDrawState(ds: TextPaint) {
                            ds.color = resources.getColor(R.color.primary_color);
                            ds.isUnderlineText = false
                        }
                    })
                    .append(item.content ?: "")
                    .create()

            }
        }

        // 优先展示主评论, 主评论不存在展示帖子
        holder.getView<TextView>(R.id.main_content_tv)?.let { textView ->
            if (item.mainComment != null) {
                textView.text = String.format("%s: %s", item.mainComment?.author?.nickname, item.mainComment?.content ?: "")
                textView.setOnClickListener {
                    item.mainComment?.let {
                        CommentReplyActivity.launch(requireContext(), commentId = it.id)
                    }
                }
            } else if (item.item != null) {
                textView.text = String.format("%s: %s", item.item?.author?.nickname, item.item?.title ?: "")
                textView.setOnClickListener {
                    item.item?.id?.let { itemId ->
                        FeedDetailActivity.launch(requireContext(), itemId = itemId)
                    }
                }
            }
        }
    }

    override fun getItemViewLayoutId(item: Comment, position: Int): Int = R.layout.comment_list_item_layout
}